#!/usr/bin/env python3
"""
Render rules by substituting {{KEY}} placeholders with values from config/rules.env.

Usage:
  python scripts/render-rules.py

Outputs to .tmp/rendered_rules, preserving relative paths.
"""
from __future__ import annotations
import os
from pathlib import Path
from typing import Dict


def load_env(env_file: Path) -> Dict[str, str]:
    kv: Dict[str, str] = {}
    if not env_file.exists():
        return kv
    for line in env_file.read_text(encoding="utf-8", errors="ignore").splitlines():
        t = line.strip()
        if not t or t.startswith("#"):
            continue
        if "=" in t:
            key, val = t.split("=", 1)
            if key.isupper():
                kv[key] = val
    return kv


def render_file(src: Path, dst: Path, kv: Dict[str, str]) -> None:
    content = src.read_text(encoding="utf-8", errors="ignore")
    for k, v in kv.items():
        content = content.replace(f"{{{{{k}}}}}", v)
    dst.parent.mkdir(parents=True, exist_ok=True)
    dst.write_text(content, encoding="utf-8")


def main() -> None:
    script_dir = Path(__file__).resolve().parent
    aid_dir = script_dir.parent  # framework root
    env_file = aid_dir / "config" / "rules.env"
    src_dir = aid_dir / "rules"
    out_dir = aid_dir / ".tmp" / "rendered_rules"

    kv = load_env(env_file)
    print(f"[render-rules] env={env_file} keys={','.join(kv.keys())}")

    count = 0
    for src in src_dir.rglob("*.md"):
        rel = src.relative_to(src_dir)
        dst = out_dir / rel
        render_file(src, dst, kv)
        count += 1

    print(f"[render-rules] done: {count} files -> {out_dir}")


if __name__ == "__main__":
    main()
